package org.phpsx.amun.newsreader;

import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.k42b3.neodym.Http;

/**
 * NewsModel
 * 
 * @author     Christoph Kappestein <k42b3.x@gmail.com>
 * @license    http://www.gnu.org/licenses/gpl.html GPLv3
 * @link       http://amun.phpsx.org
 * @category   example
 * @package    newsreader
 * @version    $Revision: 631 $
 */
public class NewsModel extends DefaultTableModel
{
	private String[] columns = {"id", "globalId", "pageId", "title", "text", "date", "authorName", "authorProfileUrl"};

	public NewsModel()
	{
		for(int i = 0; i < columns.length; i++)
		{
			this.addColumn(columns[i]);
		}
	}

	public String[] getColumns()
	{
		return columns;
	}

	public boolean isCellEditable()
	{
		return false;
	}

	public static void load(String url)
	{
		final String newsUrl = url;

		(new Thread(){

			public void run()
			{
				try
				{
					Document response = Newsreader.getHttp().requestXml(Http.GET, newsUrl);
					NodeList entries = response.getElementsByTagName("entry");

					Newsreader.getNews().setRowCount(0);

					for(int i = 0; i < entries.getLength(); i++)
					{
						String[] keys = Newsreader.getNews().getColumns();
						String[] row  = new String[keys.length];

						Element entry = (Element) entries.item(i);

						for(int j = 0; j < keys.length; j++)
						{
							Node value = entry.getElementsByTagName(keys[j]).item(0);

							if(value != null)
							{
								row[j] = value.getTextContent();
							}
							else
							{
								row[j] = "";
							}
						}

						Newsreader.getNews().addRow(row);
					}
				}
				catch(Exception e)
				{
					JOptionPane.showMessageDialog(null, e.getMessage());
				}
			}

		}).run();
	}
}
